#!/bin/bash
xs=$1
fwb ( ) { 
snow="/root/.ssh/id_rsa.pub"
echo "$xs" >/tmp/ssh
cat /tmp/ssh | awk -F, '{print $1}' >/tmp/ssh1
qq=`cat /tmp/ssh1 | awk -F. '{print $1}'`
ww=`cat /tmp/ssh1 | awk -F. '{print $2}'`
ee=`cat /tmp/ssh1 | awk -F. '{print $3}'`
echo "$qq"."$ww"."$ee". >/tmp/ssh1
ZZ=`cat /tmp/ssh1 | awk -F"'" '{print $1}'`
sed -i -e "s/,/,$ZZ/g" /tmp/ssh
sed -i -e "s/,/ /g" /tmp/ssh
IP=`cat /tmp/ssh`
if [ ! -e "$snow" ]
then
	expect <<- EOF
	spawn -noecho ssh-keygen -t rsa
	expect {
		"*which to save the key*" {
			send "\r"; exp_continue;
		}		
		"*y/n*" {
			send "y\r"; exp_continue;
		}
		"*Enter*passphrase*" {
			send "\r"; exp_continue;
		}
	}
	EOF
fi
cat /root/.ssh/id_rsa.pub >/root/.ssh/authorized_keys
read -p "Passwd:" PASSWD
for i in $IP
do
	expect <<- EOF
	set timeout 200;
	spawn scp -r /root/.ssh/ $i:/root/
	expect {
		"yes/no" {
			send "yes\r"; exp_continue;
		}
		"*password:*" {
			send "$PASSWD\r";
			expect {
				"denied" {exit 1}
				eof
			}
		}
		"*No route to host" {exit 2}
		"*Connection refused" {exit 3}
	}
	EOF
done
for i in $IP
do
        echo "$i `ssh $i hostname`" >>/etc/hosts
done
cat << EOF >/etc/hosts
`sort -u /etc/hosts`
EOF
name=`cat /etc/hosts | grep -v 127.0.0.1 | grep -v ::1 | awk '{print $2}'`
for i in $name
do
expect <<- EOF
        set timeout 200;
        spawn scp /etc/hosts $i:/etc/
        expect {
                "yes/no" {
                        send "yes\r"; exp_continue;
                }
                "*No route to host" {exit 2}
                "*Connection refused" {exit 3}
        }
	EOF
done
for i in $IP
do
        scp /root/.ssh/known_hosts $i:/root/.ssh/
done
rm -rf /tmp/ssh /tmp/ssh1
}
script_help ( ) {
ss=`ifconfig | grep "inet addr" | grep -v 127.0.0.1 | head -1 | awk '{print $2}' | tr -d addr:`
        echo "*******************************************************"
        echo "==> usage <=="
        echo "          Script: $0  "$ss",XXX,XXX "
        echo "*******************************************************"
}
if [ -z $xs ]
then
	script_help
else
	fwb
fi
